#!/bin/bash
#
# kopano-dagent Kopano Core Delivery Agent
#
# chkconfig: - 86 24
# processname: /usr/sbin/kopano-dagent
# config: /etc/kopano/dagent.cfg
# pidfile: /var/run/kopano/dagent.pid

### BEGIN INIT INFO
# Provides: kopano-dagent
# Required-Start: $local_fs $network $remote_fs $syslog
# Required-Stop: $local_fs $network $remote_fs $syslog
# Should-Start: kopano-server
# Should-Stop: kopano-server
# Short-Description: Kopano Core Delivery Agent
### END INIT INFO

DAGENTCONFIG=/etc/kopano/dagent.cfg
DAGENTPROGRAM=/usr/sbin/kopano-dagent

# Sanity checks.
[ -x $DAGENTPROGRAM ] || exit 0

# the -d option is required to run LMTP mode deamonized
DAGENTCONFIG_OPT="-d"
[ ! -z $DAGENTCONFIG -a -f $DAGENTCONFIG ] && DAGENTCONFIG_OPT="$DAGENTCONFIG_OPT -c $DAGENTCONFIG"

[ -f /etc/sysconfig/kopano ] && . /etc/sysconfig/kopano
if [ -z "$KOPANO_LOCALE" ]; then
	KOPANO_LOCALE="C"
fi

# Source function library.
. /etc/rc.d/init.d/functions

RETVAL=0
dagent=`basename $DAGENTPROGRAM`
lockfile=/var/lock/subsys/$dagent
pidfile=/var/run/kopano/dagent.pid

start() {
	# Start in background, always succeeds
	echo -n $"Starting $dagent: "
	install -dm0775 -o kopano -g kopano /var/run/kopano
	export LC_ALL=$KOPANO_LOCALE
	export LANG=$KOPANO_LOCALE
	daemon $DAGENTPROGRAM $DAGENTCONFIG_OPT
	RETVAL=$?
	unset LC_ALL LANG
	echo
	[ $RETVAL -eq 0 ] && touch $lockfile

	return $RETVAL
}

stop() {
	echo -n $"Stopping $dagent: "
	killproc $DAGENTPROGRAM
	RETVAL=$?
	echo
	[ $RETVAL -eq 0 ] && rm -f $lockfile $pidfile

	return $RETVAL
}

restart() {
	stop
	start
}

reload() {
	echo -n $"Restarting $dagent: "
	killproc $DAGENTPROGRAM -SIGHUP
	RETVAL=$?
	echo

	return $RETVAL
}

# See how we were called.
case "$1" in
    start)
		start
		;;
    stop)
		stop
		;;
    status)
		status $dagent
		RETVAL=$?
		;;
    restart|force-reload)
		restart
		;;
    condrestart|try-restart)
		if [ -f ${pidfile} ]; then
			stop
			start
		fi
		;;
    reload)
		reload
		;;
    *)
		echo $"Usage: $dagent {start|stop|status|reload|restart|condrestart|force-reload|try-restart}"
		RETVAL=1
		;;
esac

exit $RETVAL
